package com.zhihu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhihu.client.LikeClient;
import com.zhihu.pojo.Comments;
import com.zhihu.pojo.User;
import com.zhihu.pojo.baseVo.BaseResult;
import com.zhihu.utils.HeaderUtils;
import com.zhihu.utils.RedisKeyUtils;
import com.zhihu.dao.CommentsDao;
import com.zhihu.dao.CommentsRepository;
import com.zhihu.service.CommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class CommentsServiceImpl implements CommentsService {

    @Autowired
    HeaderUtils headerUtils;

    @Autowired
    CommentsRepository commentsRepository;

    @Autowired
    CommentsDao commentsDao;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    LikeClient likeClient;

    //添加评论，需要字段：评论内容；被评论用户id；被评论用户的名字；被评论用户的头像
    //被评论作品/评论的类型opusTap;作品/评论的id
    @Override
    public BaseResult insertComments(Comments comments, HttpServletRequest request) {
        BaseResult baseResult = new BaseResult();
        String userJson = headerUtils.getUserJson(request);
        User user = JSONObject.parseObject(userJson, User.class);
        if (user!=null){
            comments.setUserId(user.getUserId());
            comments.setCommUserName(user.getUserName());
            comments.setCommUserImg(user.getImg());
            comments.setCommCreatetime(new Date());
            comments.setCommLikenum(0);
            comments.setCommStatus(1);
            Comments comments1 = commentsRepository.saveAndFlush(comments);
            if (comments1!=null){
                //将评论的点赞数初始化到redis中默认为0
                likeClient.insertOpusLikeNums(5,comments1.getCommentsId());
                baseResult.setCode(0);
                baseResult.setMsg("评论成功！");
                return baseResult;
            }else {
                baseResult.setCode(1);
                baseResult.setMsg("评论失败！");
                return baseResult;
            }
        }
        baseResult.setCode(1);
        baseResult.setMsg("请先登录！");
        return baseResult;
    }

    //根据作品/评论的id来查询对应的评论，按照时间顺序排序（越早的排的越靠前）默认
    @Override
    public BaseResult findCommentsTimeSort(Integer followOpusTap, Integer followOpusId) {
        BaseResult baseResult = new BaseResult();
        List<Comments> commentsList = commentsDao.findCommentsTimeSort(followOpusTap, followOpusId);
        if (!commentsList.isEmpty()){
            baseResult.setCode(0);
            baseResult.setMsg("查询评论成功！");
            baseResult.setData(commentsList);
            return baseResult;
        }else {
            baseResult.setCode(1);
            baseResult.setMsg("还没有人评论哦！");
            return baseResult;
        }
    }

    //根据作品/评论的类型id和id来查询对应的评论，按照点赞顺序排序（越高越靠前）默认
    @Override
    public BaseResult findCommentsLikeNumSort(Integer followOpusTap, Integer followOpusId) {
        BaseResult baseResult = new BaseResult();
        //先查询出作品/评论对应的评论List
        List<Comments> list = commentsRepository.findByFollowOpusTapAndFollowOpusId(followOpusTap, followOpusId);
        if (!list.isEmpty()) {
            //因为数据库中的点赞数有可能未从redis中更新，所以这里从redis里将查询出的comments点赞字段更新
            for (Comments comments:list) {
                String key = RedisKeyUtils.getLikedOpusCountKey(comments.getCommentsId().toString(), "5");
                Integer likenums  = (Integer) redisTemplate.opsForHash().get(RedisKeyUtils.MAP_USER_OPUS_COUNT, key);
                comments.setCommLikenum(likenums);
                //更新字段
                commentsRepository.saveAndFlush(comments);
            }
            //所有评论字段更新后，再依照点赞数排序查询封装到集合中
            List<Comments> commentsList = commentsDao.findCommentsLikeNumSort(followOpusTap, followOpusId);
            if (!commentsList.isEmpty()){
                baseResult.setCode(0);
                baseResult.setMsg("查询评论成功！");
                baseResult.setData(commentsList);
                return baseResult;
            }else {
                baseResult.setCode(1);
                baseResult.setMsg("还没有人评论哦！");
                return baseResult;
            }
        }
        baseResult.setCode(1);
        baseResult.setMsg("还没有人评论哦！");
        return baseResult;
    }
}
